package com.project.service;

import com.project.dao.ClassMapper;
import com.project.entity.Class;
import com.project.entity.StudentInfo;
import com.project.service.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by WheelChen on 2017/4/19.
 */
//让checked例外也回滚
@Transactional(rollbackFor=Exception.class)
@Service
public class ClassServiceImpl extends BaseService implements ClassService {
    @Autowired
    private StudentInfoService studentInfoService;

    private static ClassMapper classMapper = null;
    public void setMapper()
    {
        if(classMapper==null)
            classMapper = sqlSessionTemplate.getMapper(ClassMapper.class);//1.获取相关mapper
    }

    @Override
    public int add(Class classroom) {
        setMapper();
        return classMapper.insertSelective(classroom);
    }

    @Override
    public int removeOne(Integer id) {
        setMapper();
        return classMapper.deleteByPrimaryKey(id);
    }

    /** Todo 如何判断是否成功
     * author: WheelChen
     * date: 2017/9/16
     * function: 删除班级及班级下的所有学生信息
     *
     * @param id
     * @return
     */
    @Override
    public boolean removeOneChain(Integer id) {
        //先删除班级表记录
        removeOne(id);
        //查出班级下的学生表信息
        List<StudentInfo> studentInfoList = studentInfoService.findBatchByClassId(id);
        //删除学生表信息
        studentInfoService.removeBatchByClassId(id);


        return true;
    }

    @Override
    public int modify(Class classroom) {
        setMapper();
        return classMapper.updateByPrimaryKeySelective(classroom);
    }

    @Override
    public Class findOne(Integer id) {
        setMapper();
        return classMapper.selectByPrimaryKey(id);
    }

    /**
     * author: WheelChen
     * date: 2017/7/13
     * function: 根据专业id批量查找班级
     *
     * @param majorid 专业表id
     * @return
     */
    @Override
    public List<Class> findBatchByMajorid(Integer majorid) {
        setMapper();
        return classMapper.selectByMajorid(majorid);
    }

    /**
     * author: WheelChen
     * date: 2017/7/25
     * function: 根据学院id批量查找班级
     *
     * @param schoolId 学院id
     * @return
     */
    @Override
    public List<Class> findBatchBySchoolId(Integer schoolId) {
        setMapper();
        return classMapper.selectBatchBySchoolId(schoolId);
    }

    /**
     * author: WheelChen
     * date: 2017/8/10
     * function: 检查班级是否已存在
     *
     * @param clazz
     * @return true - 存在 false - 不存在
     */
    @Override
    public boolean checkClassIsExist(Class clazz) {
        setMapper();
        return classMapper.checkClassIsExist(clazz) != 0;
    }


}
